'use strict';

const { WorkloadModuleBase } = require('@hyperledger/caliper-core');

class MyWorkload extends WorkloadModuleBase {
    constructor() {
        super();
    }

    async initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext) {
        await super.initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext);

        for (let i=0; i<this.roundArguments.assets; i++) {
            const assetID = `${this.workerIndex}_${i}`;
            console.log(`Worker ${this.workerIndex}: Creating asset ${assetID}`);
            const request = {
                contractId: this.roundArguments.contractId,
                contractFunction: 'AddLedger',
                invokerIdentity: 'User1',
                contractArguments: [assetID,'','','penguin','500','11'],
                readOnly: false
            };

            await this.sutAdapter.sendRequests(request);
        }
    }

  async submitTransaction() {
    for (let i = 0; i < this.roundArguments.assets; i++) {
      const assetID = `${this.workerIndex}_${i}`;
      console.log(`Worker ${this.workerIndex}: Querying asset ${assetID}`);
      const request = {
        contractId: this.roundArguments.contractId,
        contractFunction: 'QueryLedger',
        invokerIdentity: 'User1',
        contractArguments: [assetID],
        readOnly: true,
      };

      await this.sutAdapter.sendRequests(request);
    }
  }

  async cleanupWorkloadModule() {
    for (let i = 0; i < this.roundArguments.assets; i++) {
      const assetID = `${this.workerIndex}_${i}`;
      console.log(`Worker ${this.workerIndex}: Deleting asset ${assetID}`);
      const request = {
        contractId: this.roundArguments.contractId,
        contractFunction: "DeleteLedger",
        invokerIdentity: "User1",
        contractArguments: [assetID],
        readOnly: false,
      };

      await this.sutAdapter.sendRequests(request);
    }
  }
}

function createWorkloadModule() {
    return new MyWorkload();
}

module.exports.createWorkloadModule = createWorkloadModule;

